package com.itheima.reggie.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.itheima.reggie.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

@Configuration
@Slf4j
public class MybatisPlusConfig {
    /**
     * 自动填充
     * @return
     */
    @Bean
    public MetaObjectHandler metaObjectHandler(){
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                log.debug("自动填充insertFill..." + metaObject.getClass());
                metaObject.setValue("createTime", LocalDateTime.now());
                metaObject.setValue("updateTime", LocalDateTime.now());
                //获取当前登录的id
                Long id = BaseContext.getCurrentId();
                log.info("当前登录的id：{}", id);
                metaObject.setValue("createUser", id);
                metaObject.setValue("updateUser", id);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                log.debug("字段自动填充updateFill..." + metaObject.getClass());
                metaObject.setValue("updateTime", LocalDateTime.now());
                //获取当前登录的id
                Long id = BaseContext.getCurrentId();
                log.info("当前登录的id：{}", id);
                metaObject.setValue("updateUser", id);
            }
        };
    }
    /**
     * MyBatisPlus分页配置
     */
    @Bean // 加到spring容器中
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        //插件主体
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //添加自动分页的功能
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

}
